package com.matrix.framework.core.component;

import com.matrix.framework.core.common.result.Result;
import com.matrix.framework.core.i18n.I18n;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;

import java.util.HashMap;
import java.util.Map;

/**
 * Token管理控制器
 * 
 * Copyright © 海平面工作室 版权所有
 *
 * @Author: Leo
 * @Create: 2025/06/21 12:40
 * @Since 1.2
 */
@RestController
@RequestMapping("/token")
public class TokenController {
    
    private final Jwt jwt;
    
    public TokenController(Jwt jwt) {
        this.jwt = jwt;
    }
    
    /**
     * 获取当前token状态
     * @param exchange 请求上下文
     * @return token状态信息
     */
    @GetMapping("/status")
    public Result<Map<String, Object>> getTokenStatus(ServerWebExchange exchange) {
        String token = TokenRefreshUtil.extractToken(exchange);
        if (token == null) {
            return Result.<Map<String, Object>>fail(null).message("未找到有效的token");
        }
        
        try {
            String username = jwt.extractUsername(token);
            if (username == null) {
                return Result.<Map<String, Object>>fail(null).message("无法解析token中的用户信息");
            }
            
            Jwt.TokenValidationResult validationResult = jwt.validateTokenWithResult(token, username);
            
            Map<String, Object> status = new HashMap<>();
            status.put("valid", validationResult.isValid());
            status.put("username", username);
            
            if (validationResult.isValid()) {
                long remainingTime = jwt.getRemainingTime(token);
                status.put("remainingTimeMs", remainingTime);
                status.put("remainingTimeText", TokenRefreshUtil.getReadableRemainingTime(remainingTime));
                status.put("needsRefresh", validationResult.needsRefresh());
                status.put("expirationTime", jwt.extractExpiration(token));
                
                // 如果需要续期，返回新token
                if (validationResult.needsRefresh()) {
                    status.put("newToken", validationResult.getNewToken());
                }
            }
            
            return Result.ok(status).message("token状态查询成功");
            
        } catch (Exception e) {
            return Result.<Map<String, Object>>fail(null).message("token解析失败：" + e.getMessage());
        }
    }
    
    /**
     * 手动续期token
     * @param exchange 请求上下文
     * @return 续期结果
     */
    @PostMapping("/refresh")
    public Result<Map<String, Object>> refreshToken(ServerWebExchange exchange) {
        String token = TokenRefreshUtil.extractToken(exchange);
        if (token == null) {
            return Result.<Map<String, Object>>fail(null).message("未找到有效的token");
        }
        
        try {
            String username = jwt.extractUsername(token);
            String userId = jwt.extractUserId(token);
            
            if (username == null || userId == null) {
                return Result.<Map<String, Object>>fail(null).message("无法解析token中的用户信息");
            }
            
            // 验证当前token是否有效
            if (!jwt.validateToken(token, username)) {
                return Result.<Map<String, Object>>fail(null).message("当前token已失效，无法续期");
            }
            
            // 生成新token
            String newToken = jwt.generateToken(userId, username);
            
            Map<String, Object> result = new HashMap<>();
            result.put("newToken", newToken);
            result.put("username", username);
            result.put("userId", userId);
            result.put("expirationTime", jwt.extractExpiration(newToken));
            
            // 在响应头中设置新token
            TokenRefreshUtil.setNewTokenInResponse(exchange.getResponse(), newToken);
            
            return Result.ok(result).message("token续期成功");
            
        } catch (Exception e) {
            return Result.<Map<String, Object>>fail(null).message("token续期失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取token配置信息
     * @return token配置信息
     */
    @GetMapping("/config")
    public Result<Map<String, Object>> getTokenConfig() {
        Map<String, Object> config = new HashMap<>();
        config.put("expirationTime", Jwt.JWT_EXPIRATION);
        config.put("refreshThreshold", Jwt.REFRESH_THRESHOLD);
        config.put("expirationTimeText", TokenRefreshUtil.getReadableRemainingTime(Jwt.JWT_EXPIRATION));
        config.put("refreshThresholdText", TokenRefreshUtil.getReadableRemainingTime(Jwt.REFRESH_THRESHOLD));
        
        return Result.ok(config).message("token配置信息获取成功");
    }
} 